import React, { useState, useEffect, useContext } from "react";
import Header from "../../components/Header/Header";
import { $pre } from "../../http/http";
import "./Shop.less";
import { MyContext } from "../../App";
import yImg from "../../assets/img/y.jpeg";
import nImg from "../../assets/img/n.jpeg";
import { reqcartlist, reqcartedit, reqcartdelete } from "../../http/api";
import {
  Button,
  SwipeAction,
  Dialog,
  Toast,
  Stepper,
  Checkbox,
} from "antd-mobile";

export default function Cate(props) {
  const [cartList, setCartList] = useState([]);
  const [allChecked, setAllchecked] = useState(false);
  const {
    state: {
      userInfo: { uid },
    },
  } = useContext(MyContext);
  useEffect(() => {
    getCart();
  }, []);
  let getCart = () => {
    // let uid = JSON.parse(sessionStorage.getItem('userInfo')).uid;
    reqcartlist({ uid }).then((res) => {
      let list = res.data.list[1].content ? res.data.list[1].content : [];
      list.forEach((item) => {
        let obj = cartList.find((i) => i.id === item.id);
        item.checked = obj ? obj.checked : false;
      });
      setCartList(list);
      setAllchecked(
        list.length > 0 ? list.every((item) => item.checked) : false
      );
    });
  };
  // 数量 + -
  let setNum = async (value, num, id) => {
    if (value > num) {
      let res = await reqcartedit({ id, type: 2 });
    } else {
      let res = await reqcartedit({ id, type: 1 });
    }
    getCart();
  };
  // 删除
  let del = (id) => {
    reqcartdelete({ id }).then((res) => {
      getCart();
      Toast.show({
        content: res.data.msg,
      });
    });
  };
  // 点了全选
  let changeAll = (val) => {
    setAllchecked(val);

    cartList.forEach((item) => (item.checked = val));
    setCartList(cartList);
  };
  // 点击其中每一个
  let changeOne = (val, id) => {
    let obj = cartList.find((item) => item.id === id);
    obj.checked = val;
    setCartList([...cartList]);
    let flag = cartList.every((item) => item.checked);
    setAllchecked(flag);
  };
  // 总价
  let price = cartList.reduce((val, item) => {
    return item.checked ? val + item.num * item.price : val;
  }, 0);
  return (
    <div>
      <Header title="购物车"></Header>
      {cartList.map((item) => (
        <SwipeAction
          key={item.id}
          closeOnAction={false}
          closeOnTouchOutside={false}
          rightActions={[
            {
              key: "delete",
              text: "删除",
              color: "danger",
              onClick: async () => {
                await Dialog.confirm({
                  content: "确定要删除吗？",
                  onConfirm: () => {
                    del(item.id);
                  },
                });
              },
            },
          ]}
        >
          <div className="item">
            <Checkbox
              onChange={(val) => {
                changeOne(val, item.id);
              }}
              checked={item.checked}
            ></Checkbox>
            <img className="img" src={$pre + item.img} alt="" />
            <div className="right">
              <h3>name:{item.goodsname}</h3>
              <div>price:{item.price}</div>
              <div>
                <Stepper
                  value={item.num}
                  inputReadOnly
                  min={1}
                  onChange={(value) => {
                    setNum(value, item.num, item.id);
                  }}
                />
              </div>
            </div>
          </div>
        </SwipeAction>
      ))}

      {/* 全选总价 */}
      <div className="footer">
        <Checkbox
          disabled={cartList.length == 0}
          checked={allChecked}
          onChange={(val) => {
            changeAll(val);
          }}
        >
          全选
        </Checkbox>
        <div className="allPrice">￥{price.toFixed(2)}</div>
      </div>
    </div>
  );
}
